const {slugify} =require('transliteration');
const Base = require('./base.js');
const md5 = require("md5");


const moment =require("moment");
const uuid =require("node-uuid");
const fs =require( "fs-promise");


module.exports = class extends Base {

    async _initialize() {
        await super._initialize();
    }

    async galleryAction() {
        const p = this.query('page') || 1;
        let Model = this.mongoose('Picture');
        let result = await Model.findPage({
            page: p,
            pageSize: 12
        }, '', {}, {}, {updatedAt: 'desc'});

        this.assign({
            records: result.data,
            pager: super.ajaxPage(p, result.pagination.rowCount, result.pagination.pageSize, 'get_page')
        });
        await this.display('admin/picture/gallery');
    }

    async galleryTableAction() {
        const p = this.query('page') || 1;
        let Picture = this.mongoose('Picture');
        let result = await Picture.findPage({
            page: p,
            pageSize: 12
        }, '', {}, {}, {updatedAt: 'desc'});
        this.assign({
            records: result.data,
            pager: super.ajaxPage(p, result.pagination.rowCount, result.pagination.pageSize, 'get_page')
        });

        // console.log(this.assign());

        await this.display('admin/picture/gallery_table');
    }

    async deleteAction() {
        const id = this.post('id') || "";
        const ids = id.split(',');

        for (const i in ids) {
            const Picture = this.mongoose('Picture');
            const entity = await  Picture.findById(ids[i]);
            if (entity && entity.storage === "local") {
                let path = `www/public/uploads/${entity.savePath}${entity.saveName}`;
                // console.log(path);
                try{
                    if (await fs.exists(path)) {
                        await fs.unlink(path, function (err) {
                            think.logger.error(err);
                        });
                    }
                }catch(err){
                    think.logger.error(err);
                }

                entity.remove();
                this.success('','删除成功');
                return;
            }else if (entity && entity.storage === "qiniu") {
                //云存储要删除云上的文件，需要调用SDK删除
                // Picture.findByIdAndRemove(ids[i]);
                this.error('','不能删除云存储上的文件');
                return;
            }
        }

        this.error('','删除失败');

    }

    async addAction() {

        const files = this.file();

        let Model = this.mongoose('Picture');
        for (let i in files) {
            const file = files[i];
            // console.log(file);
            // const result = await Model.uploadImage(file);
            // if (result){
            //     this.json('/admin/picture/gallery','保存成功');
            //     console.log("image upload success!");
            // } else {
            //     this.json('/admin/picture/gallery', '保存失败');
            //     console.log("upload image fail!");
            // }

            let ext = '';  //后缀名
            switch (file.type) {
                case 'image/pjpeg':
                    ext = 'jpg';
                    break;
                case 'image/jpeg':
                    ext = 'jpg';
                    break;
                case 'image/png':
                    ext = 'png';
                    break;
                case 'image/x-png':
                    ext = 'png';
                    break;
            }
            const savepath = moment().format('YYYY-MM-DD') + '/';
            const savename = uuid.v1() + '.' + ext;

            //计算md5校验值，如果相同则不保存新的
            let buf = await fs.readFile(file.path);
            let checksum_md5 = think.md5(buf);
            let Model = this.mongoose('Picture');
            if (await Model.findOne({md5: checksum_md5})) {
                //existed the same file
                await fs.unlink(file.path);
                this.fail(4001,'文件已经存在');
            } else {
                const err = await fs.move(file.path, 'www/public/uploads/' + savepath + savename);
                if (!err) {
                    const data = {
                        name: file.name,
                        ext: ext,
                        fileType: file.type,
                        saveName: savename,
                        savePath: savepath,
                        storage: 'local',
                        md5: checksum_md5
                    };

                    await Model.saveOrUpdate(data);
                    this.success('/admin/picture/gallery','保存成功');
                    // console.log("success!");
                } else {
                    this.fail('','保存失败');
                    // console.log("fail!");
                }
            }
        }
    }

    async indexAction() {

        this.assign({
            storages: [{key: 'local', title: '本地存储'}, {key: 'qiniu', title: '七牛云存储'}]
        });

        await this.display('admin/picture/index');
    }

    /**
     * 加载数据表模板，生成HTML返回给前端展示
     * @returns {Promise<void>}
     */
    async tableAction() {
        const p = this.query('page') || 1;

        const id = this.post('id');
        const storage = this.post('storage');
        const keywords = this.post('keywords');

        //构造查询条件
        let queryParams = {};

        //正则表达式查询
        if (keywords !== "") {
            queryParams = {
                $or: [
                    {name: {$regex: keywords, $options: "$i"}},
                    {saveName: {$regex: keywords, $options: "$i"}},
                    {savePath: {$regex: keywords, $options: "$i"}}
                ]
            }
        }

        //等值查询
        if (storage !== "") {
            queryParams = Object.assign(queryParams, {storage: storage});
        }

        //id属性要单独查找,不支持正则表达式
        if (id !== "") {
            try {
                queryParams = {
                    _id: think.Mongoose.mongoose.Types.ObjectId(id)
                }
            } catch (err) {
                this.fail(4001,'没找到符合条件的记录');
                return;
            }
        }


        console.log(`search queryParams:${JSON.stringify(queryParams)}`);

        const pageSize= await this.mongoose('Config').C('LIST_ROWS');
        let Model = this.mongoose('Picture');
        let result = await Model.findPage({
            page: p,
            pageSize: pageSize
        }, '', queryParams, {}, {_id: 'desc'});

        this.assign({
            records: result.data,
            pager: super.ajaxPage(p, result.pagination.rowCount, result.pagination.pageSize, 'get_page')
        });

        await this.display('admin/picture/table');
    }


}
